package com.wsc.springbootmultidevdemo.msg.dlx;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 死信消费端
 */
public class Receive {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        String exchange = "dlx_test_exc";
        String routingKey = "dlx.#";
        String queue = "dlx_test_queue";

        channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC);

        //队列声明
        Map<String,Object> arguments = new HashMap<String, Object>();
        //如果出现了死信，就将消息 publish 到 dlx.exchange 上
        arguments.put("x-dead-letter-exchange","dlx.exchange");

        //argument 需要声明在队列上
        channel.queueDeclare(queue,false,false,false,arguments);
        channel.queueBind(queue,exchange,routingKey);

        //死信队列的声明
        channel.exchangeDeclare("dlx.exchange",BuiltinExchangeType.TOPIC);
        channel.queueDeclare("dlx.queue", false, false, false, null);
        channel.queueBind("dlx.queue", "dlx.exchange", "#");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"utf-8");
                System.out.println("[X] received a message :" +msg);
            }
        };
        channel.basicConsume(queue, true, consumer);

    }
}
